package com.android.mytableview.table

import android.icu.text.Transliterator.Position
import android.provider.Settings.Global
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.ViewGroup
import android.widget.EditText
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
import com.android.mytableview.R
import com.android.mytableview.bean.TableBean
import com.android.mytableview.util.LetterUtil
import com.chad.library.adapter.base.BaseDelegateMultiAdapter
import com.chad.library.adapter.base.delegate.BaseMultiTypeDelegate
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.flexbox.FlexboxLayoutManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch

class TableAdapter(data: MutableList<TableBean>) :
    BaseDelegateMultiAdapter<TableBean, BaseViewHolder>(data) {

    private val typeOne = 0
    private val typeRowHead = 1
    private val typeColumnHead = 2
    private val typeContent = 3
    private val typeRowHeadAdd = 4
    private val typeColumnHeadAdd = 5
    private val typeNull = 6

    private var activity:AppCompatActivity?=null
    private var width = 0
    private var height = 0
    private var row = 0
    private var column = 0

    //添加列
    private var onColumnAddItem: () -> Unit = { }

    fun setOnColumnAddItem(action: () -> Unit) {
        this.onColumnAddItem = action
    }

    //添加行
    private var onRowAddItem: () -> Unit = {  }

    fun setOnRowAddItem(action: () -> Unit) {
        this.onRowAddItem = action
    }

    //选中列
    private var onSelectColumnItem: (isSelect:Boolean,width:Int,height:Int,left:Int,top:Int) -> Unit = {
            _:Boolean,_:Int,_:Int,_:Int,_:Int->
    }

    fun setOnSelectColumnItem(action: (isSelect:Boolean,width:Int,height:Int,left:Int,top:Int) -> Unit) {
        this.onSelectColumnItem = action
    }

    //选中行
    private var onSelectRowItem: (isSelect:Boolean,width:Int,height:Int,left:Int,top:Int) -> Unit = {
            _:Boolean,_:Int,_:Int,_:Int,_:Int->
    }

    fun setOnSelectRowItem(action: (isSelect:Boolean,width:Int,height:Int,left:Int,top:Int) -> Unit) {
        this.onSelectRowItem = action
    }

    //选中行
    private var onSelectContentItem: (isSelect:Boolean,width:Int,height:Int,left:Int,top:Int) -> Unit = {
            _:Boolean,_:Int,_:Int,_:Int,_:Int->
    }

    fun setOnSelectContentItem(action: (isSelect:Boolean,width:Int,height:Int,left:Int,top:Int) -> Unit) {
        this.onSelectContentItem = action
    }

    //全部选中
    private var onNoSelected: () -> Unit = {
    }

    fun setOnNoSelected(action: () -> Unit) {
        this.onNoSelected = action
    }

    init {
        setTypeDelegate()
    }

    /**
     * 设置代理
     */
    private fun setTypeDelegate(){
        // 第一步，设置代理
        setMultiTypeDelegate(object : BaseMultiTypeDelegate<TableBean>() {
            override fun getItemType(data: List<TableBean>, position: Int): Int {
                return when {
                    position == 0 -> {
                        typeOne
                    }

                    data[position].row == 0 -> {
                        if (position == column - 1){
                            typeRowHeadAdd
                        }else{
                            typeRowHead
                        }
                    }

                    data[position].column == 0 -> {
                        if (position == row * column - column){
                            typeColumnHeadAdd
                        }else{
                            typeColumnHead
                        }

                    }

                    position % column == column - 1 || position > (row-1) * column ->{
                        typeNull
                    }

                    else -> {
                        typeContent
                    }
                }
            }
        })
        // 第二步，绑定 item 类型
        getMultiTypeDelegate()?.let {
            it.addItemType(typeOne, R.layout.layout_table_one)
            it.addItemType(typeRowHead, R.layout.layout_table_row_head)
            it.addItemType(typeColumnHead, R.layout.layout_table_column_head)
            it.addItemType(typeContent, R.layout.layout_table_content)
            it.addItemType(typeRowHeadAdd, R.layout.layout_table_head_add)
            it.addItemType(typeColumnHeadAdd, R.layout.layout_table_head_add)
            it.addItemType(typeNull, R.layout.layout_table_null)
        }
    }

    constructor(
        activity: AppCompatActivity,
        data: MutableList<TableBean>,
        width:Int,
        height:Int,
        row:Int,
        column: Int
    ):this(data){
        this.activity = activity
        this.width = width
        this.height = height
        this.row = row
        this.column = column
    }


    override fun convert(holder: BaseViewHolder, item: TableBean) {
        var layoutParams:ViewGroup.LayoutParams = holder.itemView.layoutParams
        layoutParams.width = item.width
        layoutParams.height = item.height
        holder.itemView.layoutParams = layoutParams

//        setItemListener(holder, item)

        holder.itemView.setOnClickListener {
            Log.e("TableAdapter","pos=${holder.adapterPosition} row=${item.row} column=${item.column} text=${item.text}")
            if (item.row == 0){
                //选中列
                selectedColumn(holder,item)

                val view = holder.itemView
                val width = view.width
                val height = view.height
                val left = view.left
                val top = view.top
                onSelectColumnItem.invoke(item.isSelected,width, height, left, top)

            }else if (item.column == 0){
                //选中行
                selectedRow(holder,item)
                val view = holder.itemView
                val width = view.width
                val height = view.height
                val left = view.left
                val top = view.top
                onSelectRowItem.invoke(item.isSelected,width, height, left, top)
            }else if (item.row in 1 until this.row-1 && item.column in 1 until  this.column-1){
                //中间表格
                selectedContent(holder,item)
                val view = holder.itemView
                val width = view.width
                val height = view.height
                val left = view.left
                val top = view.top
                onSelectContentItem.invoke(item.isSelected,width,height, left, top)
            }else{
                noSelected()
                onNoSelected.invoke()
            }
        }

        when(holder.itemViewType){
            typeOne->{
                val paddingRight = (item.width / 5f).toInt()
                val paddingBottom = (item.height / 5f).toInt()
                holder.itemView.setPadding(0,0,paddingRight,paddingBottom)
            }
            typeRowHead->{
                val paddingBottom = (item.height / 5f).toInt()
                holder.itemView.setPadding(0,0,0,paddingBottom)
                holder.setText(R.id.tv_item_table_row_head,item.text)
                if (holder.adapterPosition == 1){
                    if (item.isSelected){
                        holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_row_header_left_sel)
                    }else{
                        holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_row_header_left)
                    }
                }else if (holder.adapterPosition == column - 1 - 1){
                    if (item.isSelected){
                        holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_row_header_right_sel)
                    }else{
                        holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_row_header_right)
                    }
                }else{
                    if (item.isSelected){
                        holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_header_center_sel)
                    }else{
                        holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_header_center)
                    }
                }
            }
            typeColumnHead->{
                val paddingRight = (item.width / 5f).toInt()
                holder.itemView.setPadding(0,0,paddingRight,0)
                holder.setText(R.id.tv_item_table_column_head,item.text)
                if (holder.adapterPosition == column){
                    if (item.isSelected){
                        holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_column_header_top_sel)
                    }else{
                        holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_column_header_top)
                    }
                }else if (holder.adapterPosition == data.size - column * 2){
                    if (item.isSelected){
                        holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_column_header_bottom_sel)
                    }else{
                        holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_column_header_bottom)
                    }
                }else{
                    if (item.isSelected){
                        holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_header_center_sel)
                    }else{
                        holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_header_center)
                    }
                }
            }
            typeRowHeadAdd->{
                val paddingLeft = (item.width / 5f).toInt()
                val paddingBottom = (item.height / 5f).toInt()
                holder.itemView.setPadding(paddingLeft,0,0,paddingBottom)
                holder.itemView.setOnClickListener {
                    //添加列
                    onColumnAddItem.invoke()
                }
            }
            typeColumnHeadAdd->{
                val paddingTop = (item.height / 5f).toInt()
                val paddingRight = (item.width / 5f).toInt()
                holder.itemView.setPadding(0,paddingTop,paddingRight,0)
                holder.itemView.setOnClickListener {
                    //添加行
                    onRowAddItem.invoke()
                }
            }
            typeNull->{

            }
            else->{
                val et = holder.getView<EditText>(R.id.tv_item_table_content)
                holder.setText(R.id.tv_item_table_content,item.text)
                et.setSelection(et.text.length)
                et.addTextChangedListener(object : TextWatcher {
                    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

                    override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                        data[holder.adapterPosition].text = s.toString()
                    }

                    override fun afterTextChanged(s: Editable?) {

                    }
                })
                if (item.isSelected){
                    holder.setBackgroundResource(R.id.rl_item_table_content,R.drawable.bg_item_table_content_sel)
                }else{
                    holder.setBackgroundResource(R.id.rl_item_table_content,R.drawable.bg_item_table_content_nor)
                }
            }
        }
    }

    override fun convert(holder: BaseViewHolder, item: TableBean, payloads: List<Any>) {
        super.convert(holder, item, payloads)
        for (payload in payloads){
            when(payload){
                R.id.rl_item_table_row_head->{
                    if (holder.adapterPosition == 1){
                        if (item.isSelected){
                            holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_row_header_left_sel)
                        }else{
                            holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_row_header_left)
                        }
                    }else if (holder.adapterPosition == column - 1 - 1){
                        if (item.isSelected){
                            holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_row_header_right_sel)
                        }else{
                            holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_row_header_right)
                        }
                    }else{
                        if (item.isSelected){
                            holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_header_center_sel)
                        }else{
                            holder.setBackgroundResource(R.id.rl_item_table_row_head,R.drawable.bg_table_header_center)
                        }
                    }
                }

                R.id.rl_item_table_column_head->{
                    if (holder.adapterPosition == column){
                        if (item.isSelected){
                            holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_column_header_top_sel)
                        }else{
                            holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_column_header_top)
                        }
                    }else if (holder.adapterPosition == data.size - column * 2){
                        if (item.isSelected){
                            holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_column_header_bottom_sel)
                        }else{
                            holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_column_header_bottom)
                        }
                    }else{
                        if (item.isSelected){
                            holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_header_center_sel)
                        }else{
                            holder.setBackgroundResource(R.id.rl_item_table_column_head,R.drawable.bg_table_header_center)
                        }
                    }
                }

                R.id.rl_item_table_content->{
                    if (item.isSelected){
                        holder.setBackgroundResource(R.id.rl_item_table_content,R.drawable.bg_item_table_content_sel)
                    }else{
                        holder.setBackgroundResource(R.id.rl_item_table_content,R.drawable.bg_item_table_content_nor)
                    }
                }
            }
        }
    }


    fun getWidth():Int{
        return width
    }

    fun getHeight():Int{
        return height
    }

    fun getColumn():Int{
        return column
    }

    fun getRow():Int{
        return row
    }

    /**
     * 添加列
     */
    fun addColumn(width: Int,list:MutableList<TableBean>){
        this.column = this.column+1
        this.width = width
        data = list
        notifyDataSetChanged()
    }

    /**
     * 添加行
     */
    fun addRow(height: Int,list:MutableList<TableBean>){
        this.height = height
        this.row = this.row+1
        data = list
        notifyDataSetChanged()
    }

    /**
     * 选中列
     */
    private fun selectedColumn(holder: BaseViewHolder, item: TableBean){
        if (item.row == 0 && item.column == 0) {
            for (bean in data){
                bean.isSelected = false
            }
            notifyDataSetChanged()
            return
        }
        item.isSelected = !item.isSelected
        notifyItemChanged(holder.adapterPosition,R.id.rl_item_table_row_head)
        if (item.isSelected){
            for (index in data.indices){
                val table = data[index]
                if (table.row == 0 && table.column == 0) continue
                if (table.row == 0 && table.column > 0
                    && table.column != item.column
                    && table.column != this.column - 1 ){
                    table.isSelected = false
                    notifyItemChanged(index,R.id.rl_item_table_row_head)
                }else{
                    if (table.row == 0 || table.row == row-1 || table.column == column - 1) continue
                    if (table.row > 0 && table.column > 0){
                        table.isSelected = table.column == item.column
                        notifyItemChanged(index,R.id.rl_item_table_content)
                    }else{
                        //列
                        if (table.column == 0 && table.row < this.row - 1){
                            table.isSelected = false
                            notifyItemChanged(index,R.id.rl_item_table_column_head)
                        }
                    }

                }
            }
        }else{
            for (index in data.indices){
                val table = data[index]
                if (table.row > 0 && table.row < row - 1
                    && table.column > 0 && table.column < column - 1){
                    table.isSelected = false
                    notifyItemChanged(index,R.id.rl_item_table_content)
                }
            }
        }

    }

    /**
     * 选中行
     */
    private fun selectedRow(holder: BaseViewHolder, item: TableBean){
        if (item.row == 0 && item.column == 0) return
        item.isSelected = !item.isSelected
        notifyItemChanged(holder.adapterPosition,R.id.rl_item_table_column_head)
        if (item.isSelected){
            for (index in data.indices){
                val table = data[index]
                if (table.row == 0 && table.column == 0) continue
                if (table.column == 0 && table.row > 0
                    && table.row != item.row
                    && table.row != this.row - 1 ){
                    table.isSelected = false
                    notifyItemChanged(index,R.id.rl_item_table_column_head)
                }else{
                    if ((table.row == 0 && table.column == 0 ) || table.column == column - 1 || table.row == row - 1) continue
                    if (table.row > 0 && table.column > 0){
                        table.isSelected = table.row == item.row
                        notifyItemChanged(index,R.id.rl_item_table_content)
                    }else{
                        //列
                        if (table.row == 0 && table.column < this.column - 1){
                            table.isSelected = false
                            notifyItemChanged(index,R.id.rl_item_table_row_head)
                        }
                    }

                }
            }
        }else{
            for (index in data.indices){
                val table = data[index]
                if (table.row > 0 && table.row < row - 1
                    && table.column > 0 && table.column < column - 1){
                    table.isSelected = false
                    notifyItemChanged(index,R.id.rl_item_table_content)
                }
            }
        }
    }

    /**
     * 选中中间表格
     */
    private fun selectedContent(holder: BaseViewHolder, item: TableBean){
        if (item.row == 0 && item.column == 0) return
        item.isSelected = !item.isSelected
        for (i in data.indices){
            if (i != holder.adapterPosition){
                data[i].isSelected = holder.adapterPosition == i
            }
        }
        notifyDataSetChanged()
    }

    /**
     * 全部不选中
     */
    private fun noSelected(){
        for (item in data){
            item.isSelected = false
        }
        notifyDataSetChanged()
    }

    /**
     * 拖动
     */
    fun dragItem(dx:Int,dy:Int){
        width += dx
        height += dy

        for (i in data.indices){
            var item = data[i]
            if (item.isSelected){
                item.width = item.width + dx
                item.height = item.height + dy
                Log.e("dragItem","w=$width h=$height dx=$dx dy=$dy itemWidth=${item.width} itemHeight=${item.height}")
            }
        }
        for (bean in data){
            if (bean.row == 0 && bean.isSelected){
                var pos = bean.column + (row-1) * column
                data[pos].width = bean.width
                break
            }
        }

        /**
         * 解决高度不能小于第一次设置的高度的问题
         */
        for (bean in data){
            if (bean.column == 0 && bean.isSelected){
                var pos = bean.row * column + column - 1
                data[pos].height = bean.height
                break
            }
        }

        notifyDataSetChanged()

    }

    /**
     * 获取当前选中列的宽度
     */
    fun getSelectedColumnWidth():Int{
        for (item in data){
            if (item.isSelected && item.row == 0 && item.column > 0){
                return item.width
            }
        }
        return 0
    }

    /**
     * 获取当前选中行的高度
     */
    fun getSelectedRowHeight():Int{
        for (item in data){
            if (item.isSelected && item.column == 0 && item.row > 0){
                return item.height
            }
        }
        return 0
    }

    /**
     * 判断当前选中的是行或列
     */
    fun getIsSelectColumnRow(): selectType {
        for (item in data){
            if (item.isSelected){
                if (item.row == 0){
                    return selectType.COLUMN
                }else if (item.column == 0){
                    return selectType.ROW
                }else{
                    return selectType.NULL
                }
            }
        }
        return selectType.NULL
    }

    enum class selectType{
        NULL,COLUMN,ROW
    }

    /**
     * 获取当前选中列
     */
    fun getSelectedColumn():Int{
        for (i in data.indices){
            val item = data[i]
            if (item.row == 0 && item.isSelected){
                return item.column
            }
        }
        return 0
    }

    /**
     * 获取当前选中行
     */
    fun getSelectedRow():Int{
        for (i in data.indices){
            val item = data[i]
            if (item.column == 0 && item.isSelected){
                return item.row
            }
        }
        return 0
    }

    /**
     * 获取当前选中列的头部item
     */
    fun getSelectedColumnHeadItem():TableBean?{
        for (i in data.indices){
            val item = data[i]
            if (item.row == 0 && item.isSelected){
                return item
            }
        }
        return null
    }

    /**
     * 获取当前选中行的头部item
     */
    fun getSelectedRowHeadItem():TableBean?{
        for (i in data.indices){
            val item = data[i]
            if (item.column == 0 && item.isSelected){
                return item
            }
        }
        return null
    }

    /**
     * 删除列
     */
    fun deleteColumn(column: Int){
        this.column = this.column - 1
        this.width = this.width - data[column].width
        val iterator = data.iterator()
        while (iterator.hasNext()) {
            val item = iterator.next()
            if (item.column == column) {
                iterator.remove()
            }
        }

        for (item in data){
            if (item.column > column  ){
                item.column = item.column - 1
            }
        }

        for (item in data){
            if (item.row == 0 && item.column in 1 until this.column - 1){
                val columnHeadList = LetterUtil.generateCombinations(this.column / 26 + 1)
                item.text = "${columnHeadList[item.column - 1]}"
            }
        }
        notifyDataSetChanged()
    }

    /**
     * 删除行
     */
    fun deleteRow(row: Int){
        this.row = this.row - 1
        this.height = this.height - data[row].height
        val iterator = data.iterator()
        while (iterator.hasNext()) {
            val item = iterator.next()
            if (item.row == row) {
                iterator.remove()
            }
        }
        for (item in data){
            if (item.row > row ){
                item.row = item.row - 1
            }
        }

        for (item in data){
            if (item.column == 0 && item.row in 1 until this.row - 1){
                item.text = "${item.row}"
            }
        }
        notifyDataSetChanged()
    }

    /**
     * 获取选中范围
     */
    fun getSelectColumnRange():TableBean{
        var totalHeight = 0
        var totalWidth = 0
        var leftAdd = 0
        for (i in data.indices){
            val bean = data[i]
            if (bean.row == 0 && bean.isSelected){
                totalWidth = bean.width
                if (bean.column - 1 in 0 until  data.size){
                    totalWidth = (totalWidth + data[column - 1].width / 2f).toInt()
                    leftAdd =  (data[column - 1].width / 2f).toInt()
                }
                if (bean.column + 1 in 0 until  data.size){
                    totalWidth = (totalWidth + data[column + 1].width / 2f).toInt()
                }
            }
            if (bean.isSelected){
                totalHeight += bean.height
            }
        }
        return TableBean(width=totalWidth,height=totalHeight, leftAdd = leftAdd)
    }

    /**
     * 获取选中范围
     */
    fun getSelectRowRange():TableBean{
        var totalHeight = 0
        var totalWidth = 0
        var leftAdd = 0
        for (i in data.indices){
            val bean = data[i]
            if (bean.isSelected){
                totalWidth += bean.width
            }
        }
        return TableBean(width=totalWidth)
    }

}